const util = require('../../../utils/util.js');
const http = util.http;

Page({
  data: {
    shopParts: [],
    params: [],
    shop_id: '',
    count: 0,
  },
  // 单独设备的数量加和减
  handleReduce: function (e) {
    let id = e.target.dataset.id;
    let target = this.getNumberById(id);
    // console.log(this.data.params);
    if (this.data.params[target].number > 0) {
      let val = --this.data.params[target].number;
      let params = this.data.params;
      // console.log('success');
      this.setData({
        params
      });
    }
  },
  handlePlus: function (e) {
    let id = e.target.dataset.id;
    let target = this.getNumberById(id);
    // console.log(this.data.params);
    if (this.data.params[target].number < this.data.shopParts[target].number) {
      let val = ++this.data.params[target].number;
      let params = this.data.params;
      // console.log('success');
      this.setData({
        params
      });
    }
  },
  // 申请其他备件
  handleApplyOther: function () {
    const id = this.data.shop_id;
    wx.navigateTo({
      url: `../other/index?id=${id}`,
    })
  },
  // 提交申请
  handleApply: function () {
    var { params } = this.data;
    params = params.filter(item => item.number);
    const data = {
      shop_id: this.data.shop_id,
      param: JSON.stringify(params)
    };
    http('/parts/applyParts', 'post', data)
    .then((data) => {
      wx.showToast({
        title: '申请成功',
        icon: 'none',
      });
      wx.switchTab({
        url: '/pages/replacement/index',
      })
    })
    .catch((e) => {
      wx.showToast({
        title: e.msg || '系统出错，请稍后再试',
        icon: 'none',
      });
    })
  },
  // 利用shopID获取店铺备件列表
  onLoad: function (options) {
    var id = options.id;
    // console.log(id);
    this.setData({
      shop_id: id
    });
    const params = {
      keywor: ''
    }
    http('/parts/parts', 'post', params)
    .then((data) => {
      var newList = data.reduce(function (arr, item) {
        let newArr = arr.concat({id: item.id, number: 0});
        return newArr;
      }, []);
      this.setData({
        shopParts: data,
        params: newList
      });
    });
  },
  // 工具函数，通过id获取数据里面的对象number的值 [{id: 1,number: 0}]
  getNumberById: function (id) {
    let index;
    let target = this.data.params.forEach((item,i) => {
      if (item.id == id) {
        index = i;
      }
    });
    return index;
  },
})
